from matplotlib import cm
import pandas as pd
import numpy as np

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import io
import base64

def clean_salary(salary):
    if pd.isna(salary):
        return None
    # 去除 'k' 和 'K'
    salary = salary.replace('k', '').replace('K', '')
    # 分割薪资范围
    parts = salary.split('-')
    if len(parts) == 2:
        min_salary, max_salary = parts
        try:
            min_salary = float(min_salary)
            max_salary = float(max_salary)
            # 返回平均薪资
            return (min_salary + max_salary) / 2*1000
        except ValueError:
            return None
    return None


def education(positionName):
    print(f"education被调用 {positionName}")
    df = pd.read_csv('dataset.csv')
    # 筛选出指定岗位的数据
    df = df[df['positionName'] == positionName]

    df['education'] = df['education'].replace('不限', '不限学历')  # 统一学历名称

    # 动态计算各学历数量
    edu_counts = df['education'].value_counts().reset_index()
    edu_counts.columns = ['name', 'value']

    options = {
        "title": {"text": f"{positionName} 岗位应聘学历要求分布", "left": "center"},
        "tooltip": {"trigger": "item"},
        "legend": {"orient": "vertical", "left": "left"},
        "series": [
            {
                "name": "学历",
                "type": "pie",
                "radius": "50%",
                "data": [
                    {"value": int(edu_counts[edu_counts['name'] == category]['value']) if category in edu_counts['name'].values else 0,
                     "name": category}
                    for category in ['博士', '硕士', '本科', '大专', '不限学历']
                ],
                "emphasis": {
                    "itemStyle": {
                        "shadowBlur": 10,
                        "shadowOffsetX": 0,
                        "shadowColor": "rgba(0, 0, 0, 0.5)",
                    }
                },
            }
        ],
    }
    return options

def salary_experience():
    print("salary_experience被调用")
    # 读取数据并预处理
    df = pd.read_csv('dataset.csv')
    df['salary_numeric'] = df['salary'].apply(clean_salary)
    
    # 工作年限映射
    experience_map = {
        '不限': 0, '应届生': 0.5, '1年以下': 0.5,
        '1-3年': 2, '3-5年': 4, '5-10年': 7.5, '10年以上': 10
    }
    df['workYear_num'] = df['workYear'].map(experience_map)
    
    # 新增过滤条件：排除"不限"工作年限（即0年）
    df = df[df['workYear_num'] > 0]
    
    # 计算各工作年限的平均薪资
    salary_data = df.groupby('workYear_num')['salary_numeric'].mean().reset_index()
    
    # 构建ECharts配置
    options = {
        "title": {"text": "薪资与工作年限关系趋势", "left": "center"},
        "tooltip": {
            "trigger": "axis",
            "formatter": "工作年限: {b}年<br>平均薪资: {c}元"
        },
        "xAxis": {
            "type": "category",
            "name": "工作年限",
            "data": salary_data['workYear_num'].tolist(),
            "axisLabel": {"rotate": 45}
        },
        "yAxis": {
            "type": "value",
            "name": "平均薪资(元)",
            "axisLabel": {"formatter": "{value} 元"}
        },
        "series": [
            {
                "type": "line",
                "data": salary_data['salary_numeric'].round(2).tolist(),
                "smooth": True,
                "areaStyle": {"color": "#c23531"},
                "itemStyle": {"color": "#2f4554"},
                "lineStyle": {"width": 3}
            }
        ],
        "grid": {"containLabel": True}
    }
    
    return options

def generate_wordcloud():
    print("generate_wordcloud被调用")
    df=pd.read_csv('个性1.csv_intersection.csv')
    if df is None:
        return
    words = df.iloc[:, 0].tolist()
    # 根据词汇位置确定频率
    word_freq = {word: len(words) - index for index, word in enumerate(words)}

    # 选择一个颜色映射
    colormap = cm.get_cmap('viridis')

    # 生成词云图
    wordcloud = WordCloud(font_path='simhei.ttf', background_color='white', colormap=colormap).generate_from_frequencies(word_freq)

    # 将词云图转换为 base64 编码
    img = io.BytesIO()
    wordcloud.to_image().save(img, format='PNG')
    img.seek(0)
    img_base64 = base64.b64encode(img.getvalue()).decode()

    # 构建ECharts配置
    options = {
        "title": {"text": "词汇频率词云图", "left": "center"},
        "tooltip": {"trigger": "item"},
        "series": [
            {
                "type": "wordCloud",
                "sizeRange": [12, 60],
                "rotationRange": [-90, 90],
                "shape": 'circle',
                "textStyle": {
                    "normal": {
                        "color": "function (value) {return 'rgb(' + [Math.round(Math.random() * 255), Math.round(Math.random() * 255), Math.round(Math.random() * 255)].join(',') + ')';}"
                    },
                    "emphasis": {
                        "shadowBlur": 10,
                        "shadowColor": "#333"
                    }
                },
                "data": [{"name": word, "value": freq} for word, freq in word_freq.items()]
            }
        ]
    }
    return options


def position_count(city=None):
    print(f"position_count被调用 {city}")
    df = pd.read_csv('dataset.csv')  # 请将 'your_dataset.csv' 替换为实际的数据集文件名
    if city:
        df = df[df['city'] == city]  # 假设数据集中省份列名为 'province'

    position_counts = df['positionName'].value_counts().reset_index()
    position_counts.columns = ['name', 'value']

    options = {
        "title": {"text": f"{city if city else '所有地区'}不同岗位的职位数量", "left": "center"},
        "tooltip": {"trigger": "axis", "axisPointer": {"type": "shadow"}},
        "xAxis": {
            "type": "category",
            "data": position_counts['name'].tolist()
        },
        "yAxis": {"type": "value"},
        "series": [
            {
                "name": "职位数量",
                "type": "bar",
                "data": position_counts['value'].tolist()
            }
        ]
    }
    return options


def position_salary():
    print("position_salary被调用")
    # 读取数据并预处理
    df = pd.read_csv('dataset.csv')
    df['salary_numeric'] = df['salary'].apply(clean_salary)

    # 计算各岗位的平均薪资
    position_salary_data = df.groupby('positionName')['salary_numeric'].mean().reset_index()

    # 构建ECharts配置
    options = {
        "title": {"text": "不同岗位的薪资水平", "left": "center"},
        "tooltip": {
            "trigger": "axis",
            "formatter": "岗位: {b}<br>平均薪资: {c}元"
        },
        "xAxis": {
            "type": "category",
            "name": "岗位",
            "data": position_salary_data['positionName'].tolist(),
            "axisLabel": {"rotate": 45}
        },
        "yAxis": {
            "type": "value",
            "name": "平均薪资(元)",
            "axisLabel": {"formatter": "{value} 元"}
        },
        "series": [
            {
                "type": "bar",
                "data": position_salary_data['salary_numeric'].round(2).tolist(),
                "itemStyle": {"color": "#2f4554"}
            }
        ],
        "grid": {"containLabel": True}
    }

    return options


ST_DATA={
    "不同岗位应聘学历要求分布":(
        education,

    ),
    "薪资与工作年限关系趋势":(
        salary_experience,
    ),
    "大厂对个性的要求":(
        generate_wordcloud,
    ),
    "不同岗位的职位数量": (
        position_count,
    ),
    "不同岗位的薪资水平": (
        position_salary,
    )
}